package com.log4jviewer.ui.preferences.filters;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;

import com.log4jviewer.filters.FilterConstants;
import com.log4jviewer.filters.FilterItemModel;
import com.log4jviewer.filters.FilterItemModel.FieldType;

/**
 * Create possibility modify the Type cell in Rules Table
 * 
 * @author <a href="mailto:solid.danil@gmail.com">Daniil Lopatin</a>
 */
public class RulesFieldTypeCellEditor extends EditingSupport {

    private final TableViewer tableViewer;

    public RulesFieldTypeCellEditor(final TableViewer tableViewer) {
        super(tableViewer);
        this.tableViewer = tableViewer;
    }

    @Override
    protected CellEditor getCellEditor(final Object element) {
        return new ComboBoxCellEditor(tableViewer.getTable(), FilterConstants.LOG_FIELDS, SWT.READ_ONLY);
    }

    @Override
    protected boolean canEdit(final Object element) {
        return true;
    }

    @Override
    protected Object getValue(final Object element) {
        FilterItemModel filterItemModel = (FilterItemModel) element;
        int logFieldIndex = 0;

        for (int i = 0; i < FilterConstants.LOG_FIELDS.length; i++) {
            if (filterItemModel.getFieldType().equals(FilterConstants.LOG_FIELDS[i])) {
                logFieldIndex = i;
                break;
            }
        }
        return logFieldIndex;
    }

    @Override
    protected void setValue(final Object element, final Object value) {
        FilterItemModel filterItemModel = (FilterItemModel) element;
        FieldType[] fieldTypes = FilterItemModel.FieldType.values();
        filterItemModel.setFieldType(fieldTypes[(Integer) value]);
        tableViewer.update(element, null);
    }
}
